from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.ext.asyncio import AsyncSession
from typing import List, Optional
from pydantic import BaseModel

from config.get_db import get_db
from module_admin.entity.do.user_do import SysUser
from module_admin.entity.vo.user_vo import CurrentUserModel
from module_admin.service.login_service import LoginService
from module_user.entity.vo.bg_user_affiliate_vo import BgUserAffiliateModel, AffiliateStatsModel, InviteeInfoModel
from module_user.service.bg_user_affiliate_service import BgUserAffiliateService
from utils.response_util import ResponseUtil

router = APIRouter(prefix="/affiliate", tags=["推广返利"])

affiliate_service = BgUserAffiliateService()


@router.get("/info", summary="获取推广信息")
async def get_affiliate_info(
    db: AsyncSession = Depends(get_db),
    current_user: CurrentUserModel = Depends(LoginService.get_current_user),
):
    """获取当前用户的推广信息"""
    affiliate_info = await affiliate_service.get_or_create_affiliate_info(db, current_user.user.user_id)
    return ResponseUtil.success(data=affiliate_info)


@router.get("/stats", summary="获取推广统计")
async def get_affiliate_stats(
    db: AsyncSession = Depends(get_db),
        current_user: CurrentUserModel = Depends(LoginService.get_current_user),
):
    """获取当前用户的推广统计信息"""
    stats = await affiliate_service.get_affiliate_stats(db, current_user.user.user_id)
    return ResponseUtil.success(data=stats)


@router.get("/invitees", summary="获取被邀请人列表")
async def get_invitee_list(
    page: int = Query(1, ge=1, description="页码"),
    size: int = Query(20, ge=1, le=100, description="每页数量"),
    db: AsyncSession = Depends(get_db),
    current_user: CurrentUserModel = Depends(LoginService.get_current_user),
):
    """获取当前用户的被邀请人列表"""
    invitee_list = await affiliate_service.get_invitee_list(db, current_user.user.user_id, page, size)
    return ResponseUtil.success(data=invitee_list)


@router.get("/commissions", summary="获取返利记录")
async def get_commission_records(
    page: int = Query(1, ge=1, description="页码"),
    size: int = Query(20, ge=1, le=100, description="每页数量"),
    db: AsyncSession = Depends(get_db),
    current_user: CurrentUserModel = Depends(LoginService.get_current_user),
):
    """获取当前用户的返利记录"""
    commission_records = await affiliate_service.get_commission_records(db, current_user.user.user_id, page, size)
    return ResponseUtil.success(data=commission_records)


@router.get("/link", summary="获取推广链接")
async def get_affiliate_link(
    db: AsyncSession = Depends(get_db),
    current_user: CurrentUserModel = Depends(LoginService.get_current_user),
):
    """获取当前用户的推广链接"""
    affiliate_info = await affiliate_service.get_or_create_affiliate_info(db, current_user.user.user_id)

    # 构建推广链接
    base_url = "https://85ppt.cn"  # 这里应该是你的网站域名
    affiliate_link = f"{base_url}/register?affiliate={affiliate_info.affiliate_code}"

    return ResponseUtil.success(data = {
        "affiliate_code": affiliate_info.affiliate_code,
        "affiliate_link": affiliate_link,
        "commission_rate": affiliate_info.commission_rate
    })


class AliPayInfoUpdateRequest(BaseModel):
    """支付宝信息更新请求"""
    ali_pay_account: Optional[str] = None
    ali_pay_name: Optional[str] = None


@router.put("/ali-pay-info", summary="更新支付宝信息")
async def update_ali_pay_info(
    request: AliPayInfoUpdateRequest,
    db: AsyncSession = Depends(get_db),
    current_user: CurrentUserModel = Depends(LoginService.get_current_user),
):
    """更新当前用户的支付宝信息"""
    result = await affiliate_service.update_ali_pay_info(
        db, 
        current_user.user.user_id, 
        request.ali_pay_account, 
        request.ali_pay_name
    )
    return ResponseUtil.success(data=result)
